<template>
  <div
    class="menu-item"
    :style="indentStyle"
    @mouseenter="isHovered = true"
    @mouseleave="isHovered = false"
  >
    <div
      class="item-content"
      :class="{ 'item-hovered': isHovered, 'item-active': isActive }"
      @click="handleClick"
    >
      <span class="arrow" v-if="hasChildren">
        {{ isOpen ? "▼" : "▶" }}
      </span>
      {{ item.title }}
    </div>

    <transition name="submenu-slide">
      <div v-show="isOpen && hasChildren" class="submenu">
        <MenuItem
          v-for="child in item.children"
          :key="child.id"
          :item="child"
          :depth="depth + 1"
          :active-id="activeId"
          @item-click="emitItemClick"
        />
      </div>
    </transition>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from "vue";
import type { MenuItemType } from "./types";

const props = defineProps<{
  item: MenuItemType;
  depth: number;
  activeId?: number | null;
}>();

const emit = defineEmits<{
  (event: "item-click", id: number): void;
}>();

const isOpen = ref(false);
const isHovered = ref(false);

const hasChildren = computed(() => {
  return Array.isArray(props.item.children) && props.item.children.length > 0;
});

const isActive = computed(() => {
  return props.item.id === props.activeId;
});

const indentStyle = computed(() => ({
  // 一级菜单的左边距为 20px，二级及以后的菜单左边距也为 20px
  paddingLeft: `${props.depth === 0 ? 20 : 20}px`,
}));

const handleClick = () => {
  emit("item-click", props.item.id);
  toggleChildren();
};

const toggleChildren = () => {
  isOpen.value = !isOpen.value;
};

const emitItemClick = (id: number) => {
  emit("item-click", id);
};
</script>

<style scoped>
.menu-item {
  cursor: pointer;
  user-select: none;
  width: 100%; /* 设置固定宽度 */
  box-sizing: border-box; /* 确保 padding 不影响宽度 */
}

.item-content {
  padding: 8px;
  transition: background-color 0.2s;
  display: flex;
  align-items: center;
  width: 92%; /* 继承父元素的宽度 */
}

.item-content.item-hovered {
  width: 92%;
  background-color: #f0f0f0;
}

.item-content.item-active {
  background-color: #d0d0d0; /* 高亮背景色 */
}

.arrow {
  margin-right: 8px;
  font-size: 0.8em;
}

.submenu {
  width: 98%; /* 子菜单宽度与父菜单一致 */
  padding: 0;
  margin: 0;
}

.submenu-slide-enter-active,
.submenu-slide-leave-active {
  transition: opacity 0.3s ease, transform 0.3s ease;
}

.submenu-slide-enter-from,
.submenu-slide-leave-to {
  opacity: 0;
  transform: translateY(-10px);
}
</style>